package com.ludum.game.collision;

import com.badlogic.gdx.math.Vector2;

public class RectangleShape {
	private Vector2 leftBotCorner;
	private Vector2 rightUpCorner;
	
	RectangleShape(Vector2 pos, Vector2 size) {
		leftBotCorner = pos.cpy();
		rightUpCorner = pos.cpy().add(size);
	}
	
	public boolean testCollision(RectangleShape a, Vector2 displacement){
		if((rightUpCorner.x+displacement.x) <= a.leftBotCorner.x || 
		   (leftBotCorner.x+displacement.x) >= a.rightUpCorner.x ||
		   (rightUpCorner.y+displacement.y) <= a.leftBotCorner.y || 
		   (leftBotCorner.y+displacement.y) >= a.rightUpCorner.y){
			return false;
		}
		else{
			return true;
		}
	}
	
	public Vector2 resolveCollision(RectangleShape a, Vector2 displacement)
	{	
		if(displacement.len() < 0.000001)
			return displacement;
		Vector2 newDisplacmentX = new Vector2();
		Vector2 newDisplacmentY = new Vector2();
		
		Vector2 thisPos = (leftBotCorner.cpy().add(rightUpCorner)).scl(0.5f).add(displacement);
		Vector2 aPos = (a.leftBotCorner.cpy().add(a.rightUpCorner)).scl(0.5f);
		
		Vector2 n = thisPos.cpy().sub(aPos);
		
		/* Compute x penetration */
		float thisHalfX = (rightUpCorner.x - leftBotCorner.x) /2.f;
		float aHalfX = (a.rightUpCorner.x - a.leftBotCorner.x) /2.f;
		
		float xOverLap= thisHalfX + aHalfX - Math.abs(n.x);
		
		/* Compute y penetration */
		float thisHalfY = (rightUpCorner.y - leftBotCorner.y) /2.f;
		float aHalfY = (a.rightUpCorner.y - a.leftBotCorner.y) /2.f;
		
		float yOverLap= thisHalfY + aHalfY - Math.abs(n.y);	
		
		/* Find the most penetration */

		newDisplacmentX.y = displacement.y;
		newDisplacmentX.x = (Math.abs(displacement.x)/displacement.x)*(Math.abs(displacement.x) - xOverLap);

		newDisplacmentY.x = displacement.x;
		newDisplacmentY.y = (Math.abs(displacement.y)/displacement.y)*(Math.abs(displacement.y) - yOverLap);
		
		if(testCollision(a,newDisplacmentX))
		{
			if(testCollision(a,newDisplacmentY))
			{
				return new Vector2(0f,0f);
			}
			else
			{
				return newDisplacmentY;
			}
		}
		else
		{
			if(testCollision(a,newDisplacmentY))
			{
				return newDisplacmentX;
			}
			else
			{
				if(xOverLap < yOverLap){
					return newDisplacmentX;
				}
				else{
					return newDisplacmentY;
				}
			}
		}
	}



	public void updatePosition(Vector2 pos, Vector2 size) {
		leftBotCorner.set(pos);
		rightUpCorner.set(pos).add(size);		
	}

}
